﻿using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Cluster.LiveJournalLib;
using Microsoft.Win32;

namespace Cluster.JeJePoster
{
    public partial class UserSelectForm : Form
    {
        const string ClientName = "JeJePoster";
        readonly LiveJournalClient ljClient;
        readonly ResourceManager resources = new ResourceManager("JeJePoster.Languages", Assembly.GetExecutingAssembly());

        public UserSelectForm()
        {
            InitializeComponent();
            ljClient = new LiveJournalClient(ClientName);
            LoadUsers();
        }

        protected void LoadUsers()
        {
            string[] userNames = ljClient.GetUserList();
            int c = 0;
            imageList.Images.Clear();
            listViewJournals.Items.Clear();
            //for (int i = 1; i < 30; i++) // Just for test!
            foreach (string userName in userNames)
            {
                Bitmap bitmap;
                try
                {
                    bitmap = new Bitmap(ljClient.GetUserPic(userName));
                }
                catch
                {
                    bitmap = new Bitmap(100,100);
                }
                imageList.Images.Add(Image.FromHbitmap(bitmap.GetHbitmap()));
                var listItem = new ListViewItem(userName) {ImageIndex = c};
                listViewJournals.Items.Add(listItem);
                c++;
            }
        }
    
        void AddUser()
        {
            var addUserForm = new AddUserForm(false);
            if (addUserForm.ShowDialog() == DialogResult.OK)
            {
                var pleaseWaitForm = new PleaseWaitForm();
                pleaseWaitForm.Show();
                pleaseWaitForm.BringToFront();
                Hide();
                Cursor.Current = Cursors.WaitCursor;
                Application.DoEvents();
                //Hide();
                try
                {
                    string login = addUserForm.textBoxLogin.Text;
                    if (ljClient.UserExists(login))
                    {
                        // ReSharper disable AssignNullToNotNullAttribute
                        MessageBox.Show(string.Format(resources.GetString("UserAlreadyExists"), login),
                                        // ReSharper restore AssignNullToNotNullAttribute
                                        resources.GetString("Error"), MessageBoxButtons.OK,
                                        MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button1);
                        return;
                    }
                    ljClient.User = login;
                    ljClient.Password = addUserForm.textBoxPassword.Text;
                    ljClient.LoadData(true);
                    if (addUserForm.checkBoxSavePassword.Checked)
                    {
                        ljClient.SavePassword();
                    }
                    if (addUserForm.checkBoxAutoLogin.Checked)
                    {
                        var key =
                            Registry.CurrentUser.OpenSubKey("Software\\Cluster\\" + ClientName, true) ??
                            Registry.CurrentUser.CreateSubKey("Software\\Cluster\\" + ClientName);
                        if (key != null) key.SetValue("AutoLogin", login, RegistryValueKind.String);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message,
                                    resources.GetString("Error"), MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation,
                                    MessageBoxDefaultButton.Button1);
                }
                finally
                {
                    Show();
                    LoadUsers();
                    pleaseWaitForm.Close();
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void EditUser()
        {
            var selected = listViewJournals.SelectedIndices;
            if (selected.Count == 0)
                MessageBox.Show(resources.GetString("NeedSelectJournal"),
                                resources.GetString("Error"), MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
            else
            {
                string userName = listViewJournals.Items[selected[0]].Text;
                var editUserForm = new AddUserForm(true);
                editUserForm.Text = resources.GetString("Properties");
                editUserForm.textBoxLogin.Text = userName;
                editUserForm.textBoxLogin.ReadOnly = true;
                editUserForm.checkBoxSavePassword.Checked = ljClient.HasSavedPassword(userName);
                editUserForm.textBoxPassword.Enabled = editUserForm.checkBoxSavePassword.Checked;
                if (editUserForm.checkBoxSavePassword.Checked)
                    editUserForm.textBoxPassword.Text = "lolpassword :)";
                editUserForm.checkBoxAutoLogin.Checked = ((GetAutoLoginUser() == userName) && editUserForm.checkBoxSavePassword.Checked);
                if (editUserForm.ShowDialog() == DialogResult.OK)
                {
                    if ((editUserForm.checkBoxSavePassword.Checked) &&
                    (editUserForm.textBoxPassword.Text != "lolpassword :)"))
                    {
                        ljClient.User = userName;
                        ljClient.Password = editUserForm.textBoxPassword.Text;
                        ljClient.SavePassword();
                    }
                    if (!editUserForm.checkBoxSavePassword.Checked) ljClient.UnsavePassword(userName);
                    var key =
                                             Registry.CurrentUser.OpenSubKey("Software\\Cluster\\" + ClientName, true) ??
                                             Registry.CurrentUser.CreateSubKey("Software\\Cluster\\" + ClientName);
                    if (editUserForm.checkBoxAutoLogin.Checked)
                    {
                        if (key != null) key.SetValue("AutoLogin", userName, RegistryValueKind.String);
                    }
                    else
                    {
                        if (GetAutoLoginUser() == userName)
                        {
                            if (key != null) key.DeleteValue("AutoLogin");
                        }
                    }
                }
            }
        }

        private void RemoveUser()
        {
            var selected = listViewJournals.SelectedIndices;
            if (selected.Count == 0)
                MessageBox.Show(resources.GetString("NeedSelectJournal"),
                                resources.GetString("Error"), MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
            else
            {
                if (MessageBox.Show(resources.GetString("AreYouSure"), menuItemRemove.Text, MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    string userName = listViewJournals.Items[selected[0]].Text;
                    ljClient.RemoveUser(userName);
                    if (GetAutoLoginUser() == userName)
                    {
                        var key =
                             Registry.CurrentUser.OpenSubKey("Software\\Cluster\\" + ClientName, true) ??
                             Registry.CurrentUser.CreateSubKey("Software\\Cluster\\" + ClientName);
                        if (key != null) key.DeleteValue("AutoLogin");
                    }
                    LoadUsers();
                }
            }
        }

        private static string GetAutoLoginUser()
        {
            var key =
                 Registry.CurrentUser.OpenSubKey("Software\\Cluster\\" + ClientName, true) ??
                 Registry.CurrentUser.CreateSubKey("Software\\Cluster\\" + ClientName);
            if (key != null) return (string)key.GetValue("AutoLogin");
            return null;
        }
   
        private void menuItemAddJournal_Click(object sender, EventArgs e)
        {
            AddUser();
        }
  
        private void menuItem_Remove(object sender, EventArgs e)
        {
            RemoveUser();
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void menuItemProperties_Click(object sender, EventArgs e)
        {
            EditUser();
        }

        private void OpenUser(string userName)
        {
            Cursor.Current = Cursors.WaitCursor;
            ljClient.User = userName;
            if (ljClient.HasSavedPassword())
            {
                ljClient.LoadPassword();
                var pstoForm = new PstoForm(ljClient, null);
                pstoForm.Show();
                Hide();
                Cursor.Current = Cursors.Default;
            }
            else
            {
                var passwordForm = new PasswordForm(ljClient);
                Cursor.Current = Cursors.Default;
                passwordForm.ShowDialog();
            }
        }

        private void listViewJournals_ItemActivate(object sender, EventArgs e)
        {
            var selected = listViewJournals.SelectedIndices;
            if (selected.Count == 1)
            {
                OpenUser(listViewJournals.Items[selected[0]].Text);
            }
        }

        private void timerAutoLogin_Tick(object sender, EventArgs e)
        {
            timerAutoLogin.Enabled = false;
            string autoLogin = GetAutoLoginUser();
            if (!string.IsNullOrEmpty(autoLogin))
                OpenUser(autoLogin);
        }
    
        private void listViewJournals_SelectedIndexChanged(object sender, EventArgs e)
        {
            timerAutoLogin.Enabled = false;
        }

        private void menuItemJournals_Popup(object sender, EventArgs e)
        {
            timerAutoLogin.Enabled = false;
        }
    }
}